<?php

namespace App\Http\Controllers;

use App\Http\Requests\CreateQuestionsRequest;
use App\Http\Requests\UpdateQuestionsRequest;
use App\Models\Options;
use App\Models\Questions;
use App\Models\Temp;
use App\Repositories\QuestionsRepository;
use Illuminate\Http\Request;
use Flash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Mockery\Exception;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

class QuestionsController extends AppBaseController
{
    /** @var  QuestionsRepository */
    private $questionsRepository;

    public function __construct(QuestionsRepository $questionsRepo)
    {
        $this->questionsRepository = $questionsRepo;
    }

    /**
     * Display a listing of the Questions.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->questionsRepository->pushCriteria(new RequestCriteria($request));
        $questions = $this->questionsRepository->paginate($request->get('limit', 10));

        return view('questions.index')
            ->with('questions', $questions);
    }

    /**
     * Show the form for creating a new Questions.
     *
     * @return Response
     */
    public function create()
    {
    	$tempId = Input::get('temp_id', 0);
    	$baseData = $this->getBaseData($tempId);

        return view('questions.create', compact('baseData', 'tempId'));
    }

    private function getBaseData($tempId) {
    	$type = Questions::getType();
    	$questions = $this->questionsRepository;
    	if($tempId) $questions = $this->getQuestionsByTempId($tempId);
    	else $questions = $questions->all();

	    $temps = Temp::select('id', 'name')->pluck('name', 'id')->toArray();
	    $temps[0] = '--请选择--';
	    ksort($temps);

	    return compact('type', 'questions', 'temps');
    }

    public function getQuestionsByTempId($tempId) {
    	$cond = ['temp_id' => $tempId];
    	$tmp = $this->questionsRepository->findWhere($cond, ['id', 'content', 'code'])->groupBy('id');
    	$res = [];
    	$res[0] = '--暂无--';
    	foreach ($tmp as $k => $v) {
    		$res[$k] = $v[0]['code'] . '. ' . $v[0]['content'];
	    }

    	return $res;
    }

    /**
     * Store a newly created Questions in storage.
     *
     * @param CreateQuestionsRequest $request
     *
     * @return Response
     */
    public function store(CreateQuestionsRequest $request)
    {
        $input = $request->all();
        DB::beginTransaction();
        $question = $this->questionsRepository->findWhere(['temp_id' => $input['temp_id'], 'code' => $input['code']]);
        if($question->isNotEmpty()) {
        	Flash::error('该问卷已有' . $input['code'] . '题');
        	return redirect(route('questions.create') . '?temp_id=' . $input['temp_id']);
        }

        $questions = $this->questionsRepository->create($input);

        if($input['type'] === '1') {
	        $opArr = [];
	        foreach ($input['simple_option_code'] as $k => $v) {
		        $opArr[] = new Options([
			        'code' => $v,
			        'content' => $input['simple_option_content'][$k],
			        'score' => $input['simple_option_score'][$k],
		        ]);
	        }

	        $questions->options()->saveMany($opArr);
        } elseif ($input['type'] === '2') {
        	$opArr = [];
	        foreach ($input['multi_options'] as $v) {
		        $opArr[] = new Options([
			        'content' => $v
		        ]);
	        }

	        $questions->options()->saveMany($opArr);
        }
        DB::commit();

        Flash::success('Questions saved successfully.');

        return redirect(route('temps.show', ['id' => $input['temp_id']]) . '');
    }

    /**
     * Display the specified Questions.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $questions = $this->questionsRepository->findWithoutFail($id);

        if (empty($questions)) {
            Flash::error('Questions not found');

            return redirect(route('questions.index'));
        }

        $type = Questions::getType();

        return view('questions.show')->with('questions', $questions)->with('type', $type);
    }

    /**
     * Show the form for editing the specified Questions.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $questions = $this->questionsRepository->findWithoutFail($id);
	    $tempId = $questions->temp_id;
	    $baseData = $this->getBaseData($tempId);
        if (empty($questions)) {
            Flash::error('Questions not found');

            return redirect(route('temps.show', ['id' => $tempId]));
        }

        return view('questions.edit', compact('questions', 'tempId', 'baseData'));
    }

    /**
     * Update the specified Questions in storage.
     *
     * @param  int              $id
     * @param UpdateQuestionsRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateQuestionsRequest $request)
    {
        $questions = $this->questionsRepository->findWithoutFail($id);

        if (empty($questions)) {
            Flash::error('不存在的问题');

	        return redirect(route('temps.show', ['id' => $questions->temp_id]));
        }

        DB::beginTransaction();
        $this->enableQueryLog();
        try {
	        $this->questionsRepository->scopeQuery(function ($qu) use ($request, $id) {
        		$q = $qu;
        		$q = $q->where('temp_id', $request->get('temp_id'))
			        ->where('code', $request->get('code'))
			        ->where('id', '<>', $id);

        		return $q;
	        });

        	$question = $this->questionsRepository->get();
        	if($question->isNotEmpty()) {
        		throw new Exception('当前问卷已有' . $request->get('code') . '题');
	        }

	        # 重置查询
        	$this->questionsRepository->resetScope();
	        # 更新问题
	        $this->questionsRepository->update($request->all(), $id);
	        # 更新选项
	        $questions->options()->delete();

	        $input = $request->all();
	        if($input['type'] === '1') {
		        $opArr = [];
		        foreach ($input['simple_option_code'] as $k => $v) {
			        $opArr[] = new Options([
				        'code' => $v,
				        'content' => $input['simple_option_content'][$k],
				        'score' => $input['simple_option_score'][$k],
			        ]);
		        }

		        $questions->options()->saveMany($opArr);
	        } elseif ($input['type'] === '2') {
		        $opArr = [];
		        foreach ($input['multi_options'] as $v) {
			        $opArr[] = new Options([
				        'content' => $v
			        ]);
		        }

		        $questions->options()->saveMany($opArr);
	        }
        } catch (Exception $e) {
        	DB::rollBack();
        	Flash::error($e->getMessage());

        	return redirect(route('temps.edit', ['id' => $request->get('temp_id')]));
        }

        Flash::success('修改成功');
        DB::commit();

        return redirect(route('temps.show', ['id' => $input['temp_id']]));
    }

    /**
     * Remove the specified Questions from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $questions = $this->questionsRepository->findWithoutFail($id);

        if (empty($questions)) {
            Flash::error('Questions not found');

            return redirect(route('questions.index'));
        }

        $this->questionsRepository->delete($id);

        Flash::success('Questions deleted successfully.');

        return redirect(route('questions.index'));
    }
}
